package org.saratogaschools.edd.firefighter.client.activity;

import org.saratogaschools.edd.firefighter.client.ClientFactory;
import org.saratogaschools.edd.firefighter.client.place.FireListPlace;
import org.saratogaschools.edd.firefighter.client.place.SelectRolePlace;
import org.saratogaschools.edd.firefighter.client.util.AsyncPlaceChange;
import org.saratogaschools.edd.firefighter.client.view.SelectRoleView;
import org.saratogaschools.edd.firefighter.shared.model.FireFighter;
import org.saratogaschools.edd.firefighter.shared.model.FireFighter.FireFighterRole;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class SelectRoleActivity extends AbstractActivity implements SelectRoleView.Presenter {
	
	private FireFighter registrationCandidate;
	private ClientFactory clientFactory;

	public SelectRoleActivity(SelectRolePlace place, ClientFactory clientFactory) {
		this.registrationCandidate = place.getRegistrationCandidate();
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		SelectRoleView view = new SelectRoleView();
		view.setPresenter(this);
		panel.setWidget(view);
		view.setChiefRegistrationEnabled(clientFactory.areAdvancedFeaturesActive());
	}

	@Override
	public void registerAsChief() {
		commonRegister(FireFighterRole.CHIEF);
	}

	@Override
	public void registerAsFighter() {
		commonRegister(FireFighterRole.FIGHTER);
	}
	
	private void commonRegister(FireFighterRole role) {
		registrationCandidate.setRole(role);
		clientFactory.getService().registerFireFighter(registrationCandidate, new AsyncCallback<FireFighter>() {
			public void onFailure(Throwable caught){}
			public void onSuccess(FireFighter result) {
				GWT.runAsync(new AsyncPlaceChange(clientFactory, new FireListPlace(result)));
			}
		});
	}

}
